package com.one.controller;

import com.one.common.Result;
import com.one.mapper.DataMapper;
import com.one.pojo.data;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/data")
public class dataController {

    @Resource
    DataMapper dataMapper;

    @PostMapping("/save")
    public Result<?> save(@RequestBody data data1) {  //?表示任何类型 //RequestBody把json转换成java对象
        /**
         * 添加用户数据
         */
        dataMapper.add(data1);
        return Result.success();
    }

    @PutMapping("/update")
    public Result<?> update(@RequestBody data data1) {
        /**
         * 更新用户数据
         */
        dataMapper.updateById(data1);
        return Result.success();
    }

    @GetMapping("/limit")
    public Result<?> limit(@RequestParam(defaultValue = "1") int startIndex,
                           @RequestParam(defaultValue = "10") int pageSize) {
        /**
         * 分页查询
         */
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        if (startIndex == 1) {
            map.put("startIndex",startIndex-1);
        }else {
            map.put("startIndex",(startIndex-1)*pageSize);//分页逻辑
        }
        map.put("pageSize",pageSize);
        List<data> limit = dataMapper.limit(map);
        return Result.success(limit);
    }

    @GetMapping("/search")
    public Result<?> search(@RequestParam(defaultValue = "") String name) {
        /**
         * 根据用户名 关键字 搜索 对象数据
         */
        String name_pinjie = "%"+name+"%"; //模糊查询  拼接 %
        List<data> search_result = dataMapper.search(name_pinjie);
        return Result.success(search_result);
    }

    @GetMapping("/select")
    public Result<?> select() {
        /**
         * 查询总数居 条数
         */
        return Result.success(dataMapper.select());
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> deleteById(@PathVariable int id) {
        /**
         * 根据id 删除 数据
         */
        dataMapper.deleteById(id);
        return Result.success();
    }



}
